package com.navinfo.platform.basicdatastatistics.utils;

import com.navinfo.platform.basicdatastatistics.enums.DataTypeEnum;
import com.navinfo.platform.basicdatastatistics.enums.YardEnum;
import com.navinfo.platform.common.anno.RunningEnv;

import org.reflections.Reflections;

import java.util.HashMap;
import java.util.Map;

public class ServiceRegister {

    public static Map<String, Class<?>> implementationsMap = new HashMap<String, Class<?>>();

    static {
        new Reflections("com.navinfo.platform.basicdatastatistics.service.impl")
            .getTypesAnnotatedWith(RunningEnv.class)
            .forEach((Class<?> clazz) ->{
                RunningEnv runningEnv = clazz.getAnnotation(RunningEnv.class);
                String key = runningEnv.yard().getYardName() + "_" + runningEnv.dataType() + "_" + runningEnv.interfaceClass().getSimpleName();
                try {
                    implementationsMap.put(key,  clazz);
                } catch (Exception e) {
                    throw new RuntimeException("接口注册异常，终止运行程序", e);
                }
            });
    }

    public static <T> T getInstance(String key) {
        try{
            Class cls = implementationsMap.get(key);
            return (T) cls.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T getInstance(Map<String, String> configMap, Class clazz) {
        String runningEnv = configMap.get("runningEnv");
        YardEnum yard = YardEnum.getYardEnum(runningEnv);
        String key = ServiceRegister.buildKey(yard.getYardName(), clazz.getSimpleName());
        return getInstance(key);
    }

    public static <T> T getInstance(DataTypeEnum dataType, Map<String, String> configMap, Class clazz) {
        String runningEnv = configMap.get("runningEnv");
        YardEnum yard = YardEnum.getYardEnum(runningEnv);
        String key = ServiceRegister.buildKey(yard.getYardName(), dataType, clazz.getSimpleName());
        return getInstance(key);
    }

    public static String buildKey(Object ... objects){
        StringBuilder keyBuilder = new StringBuilder();
        for(Object obj : objects){
            keyBuilder.append(obj).append("_");
        }
        if(keyBuilder.length() > 1){
            return keyBuilder.substring(0, keyBuilder.length() - 1);
        }
        return keyBuilder.toString();
    }
}
